package com.itheima.intercept;

import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class MyIntercept  implements HandlerInterceptor {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object arg2) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                boolean b = cookie.getName().equals("login_member_telephone");
                if (b) {
                    String value = cookie.getValue();
                    // 13888888888 & 门票过期时间
                    // 这里应该做一个解密的过程
                    String[] split = value.split("&");
                    String telephone = split[0];
                    String tokenOutTime = split[1];
                    Date date = DateUtils.parseString2Date(tokenOutTime,"yyyy-MM-dd HH:mm:ss");
                    Date currentDate = new Date();
                    boolean after = date.after(currentDate);
                    if (!after) {
                        return false;
                    }
                    Jedis resource = jedisPool.getResource();
                    //取到会员的json值
                    String member = resource.get(telephone);
                    if (member == null) {
                        // 这里可以往response里面塞入一些说明，就是我们后台返回的json值
                        //{"data":null,"flag":false,"message":"登录过期"}
                        ServletOutputStream responseOutputStream = response.getOutputStream();
                        response.setContentType("application/json");//代表的是Excel文件类型
//                        responseOutputStream.print();
                        responseOutputStream.write("{\"data\":null,\"flag\":false,\"message\":\"登录过期\"}".getBytes());
                        responseOutputStream.flush();
                        responseOutputStream.close();
                        return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }

}
